package com.csbaic.web.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class LongToLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {

    public LongToLocalDateTimeDeserializer() {
        super(LocalDateTime.class);

    }

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonDeserializer longDeserializer = ctxt.findRootValueDeserializer(TypeFactory.defaultInstance().constructType(Long.class));
        Long timeInMillis = (Long) longDeserializer.deserialize(p, ctxt);

        if (timeInMillis != null) {
            return  LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timeInMillis),
                    ZoneId.of( ctxt.getTimeZone().getID())
            );
        }
        return null;
    }


}
